package com.stars.services.impl.system;

import com.stars.common.base.ResultMsg;
import com.stars.common.valid.MyException;
import com.stars.dao.mapper.system.SystemPerOrgMapper;
import com.stars.entity.dto.system.SystemPerOrgDTO;
import com.stars.entity.system.SystemPerOrgEntity;
import com.stars.services.impl.BaseConfigServiceImpl;
import com.stars.services.system.SystemPerOrgConfigServices;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: 资源与组织关系 业务逻辑
 * @author dj
 * @date 2019-10-17 20:57:37
 * @version V1.0
 *
 */
@Service
public class SystemPerOrgConfigServicesImpl  extends BaseConfigServiceImpl<SystemPerOrgMapper , SystemPerOrgEntity> implements SystemPerOrgConfigServices {

    @Autowired
    private SystemPerOrgMapper systemPerOrgMapper;
    @Override
    public ResultMsg addPerOrg(String[] orgIds, String[] perIds) throws Exception {
        List<SystemPerOrgEntity> list = addToMap(orgIds, perIds);
        for (SystemPerOrgEntity entity : list) {
            insert(entity);
        }
        return ResultMsg.success();
    }

    @Override
    public ResultMsg delPerOrg(String[] orgIds, String[] perIds) {
        List<SystemPerOrgEntity> list = addToMap(orgIds, perIds);
        for (SystemPerOrgEntity entity : list) {
            List<SystemPerOrgDTO> byOrgIdAndPerId = systemPerOrgMapper.findByOrgIdAndPerId(entity.getOrgId(), entity.getPerId());
            if(byOrgIdAndPerId.isEmpty()){
                continue;
            }
            systemPerOrgMapper.delByOrgIdAndPerId(entity);
        }

        return ResultMsg.success();
    }
    private List<SystemPerOrgEntity> addToMap(String[] orgIds, String[] perIds){
        if(null == orgIds){
            throw new MyException("没有选择组织！");
        }
        if(null == perIds){
            throw new MyException("没有选择添加资源！");
        }
        List<SystemPerOrgEntity> list = new ArrayList<>();
        Map<String,String> map = new HashMap<>();
        for (String perId : perIds) {
            if(StringUtils.isBlank(perId)){
                continue;
            }
            for (String orgId : orgIds) {
                if(StringUtils.isBlank(orgId)){
                    continue;
                }
                SystemPerOrgEntity systemPerOrgEntity = new SystemPerOrgEntity();
                systemPerOrgEntity.setPerId(perId);
                systemPerOrgEntity.setOrgId(orgId);
                list.add(systemPerOrgEntity);
            }
        }
        return list;

    }

}